<?php
class Randstand_Net_Socket_Server_Message
{
    /**
     * Line break constant
     *
     */
    const LINE_BREAK = "\r\n";
    
    /**
     * Instance holder
     *
     * @var Randstand_Net_Socket_Server_Message
     */
    private static $_instance = null;
    
    /**
     * Holds SimpleXMLElement object with all the
     * existing server messages 
     *
     * @var SimpleXMLElement
     */
    private $_serverMessages = null;
    
    
    /**
     * Returns just one instance of
     * Randstand_Net_Socket_Server_Message
     *
     * @return Randstand_Net_Socket_Server_Message
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        
        return self::$_instance;
    }
    
    
    /**
     * Constructor
     *
     */
    private function __construct()
    {
        $serverMessagesFile = dirname(__FILE__).'/../../../../../media/xml/server_messages.xml';
        
        try {
            $this->_serverMessages = new SimpleXMLElement(file_get_contents($serverMessagesFile), LIBXML_NOCDATA);
        }
        catch (Exception $e) {
            throw new Randstand_Net_Socket_Server_Exception('Couldn\'t load/parse server_messages.xml');
        }
    }
    
    
    /**
     * Returns an object with containing the message
     * and all the placeholders that need to be replaced
     *
     * @param string $argMessage
     * @return stdClass
     */
    public function getMessage($argMessage)
    {
        $msgRoot = $this->_serverMessages->$argMessage;
        
    	$oRet = new stdClass();
    	$oRet->message = (string)$msgRoot->message;
    	
    	$oRet->placeholders = array();
    	if (isset($msgRoot->placeholders->placeholder)) {
        	foreach ($msgRoot->placeholders->placeholder as $placeholder) {
        	    $oRet->placeholders[] = (string)$placeholder;
        	}
    	}
    	
    	return $oRet;
    }
    
    
    /**
     * Returns a message string with all the
     * placeholders replace by the provided arguments
     *
     * @return unknown
     */
    public function getFormattedMessage()
    {
        $args = func_get_args();
        $i = 0;
        
        $msg = $this->getMessage($args[$i++]); 
    	
        foreach ($msg->placeholders as $placeholder) {
    	    $msg->message = str_replace($placeholder, $args[$i++], $msg->message);
    	}
    	
    	return $msg->message.self::LINE_BREAK;
    }
    
}
?>